package com.mingqi.enetconnected.primary.mytask;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.base.BaseFragment;
import com.mingqi.enetconnected.data.bean.order.OrderBrief;
import com.mingqi.enetconnected.data.source.OrderDataSource;
import com.mingqi.enetconnected.data.source.OrderRepository;
import com.mingqi.enetconnected.data.source.local.OrderLocalDataSource;
import com.mingqi.enetconnected.data.source.remote.OrderRemoteDataSource;
import com.mingqi.enetconnected.primary.mytask.activity.LootAssignmentActivity;
import com.mingqi.enetconnected.primary.mytask.activity.MyScheduleActivity;
import com.mingqi.enetconnected.primary.mytask.activity.NotificationMessageActivity;
import com.mingqi.enetconnected.primary.mytask.activity.TaskDetailsActivity;
import com.mingqi.enetconnected.primary.mytask.adapter.BusinessTypeAdapter;
import com.mingqi.enetconnected.primary.mytask.adapter.MyTaskAdapter;
import com.mingqi.enetconnected.primary.mytask.event.OrderStateEvent;
import com.mingqi.enetconnected.util.DeviceUtils;
import com.mingqi.enetconnected.util.Jump2MapUtils;
import com.mingqi.enetconnected.util.helper.FragmentBackHandler;
import com.mingqi.enetconnected.util.hint.ToastUtils;
import com.mingqi.enetconnected.util.resource.ResourceUtils;
import com.mingqi.enetconnected.view.CustomLoadMoreView;
import com.mingqi.enetconnected.view.Dialog.CommonDialog;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import q.rorbin.badgeview.QBadgeView;

/**
 * 我的工作模块
 * Created by li on 2018/7/30.
 * WeChat 18571658038
 * author LiWei
 */

public class MyTaskFragment extends BaseFragment  implements FragmentBackHandler {

    private static final String TAG = MyTaskFragment.class.getSimpleName();
    @BindView(R.id.v_state)
    View mVState;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_right_more)
    ImageView mIvRightMore;
    @BindView(R.id.rg_date_choose)
    RadioGroup mRgDateChoose;
    @BindView(R.id.tv_type_show)
    TextView mTvTypeShow;
    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.ll_type_choose)
    RelativeLayout mLlTypeChoose;
    @BindView(R.id.srl_task)
    SwipeRefreshLayout mSrlTask;
    @BindView(R.id.rv_task)
    RecyclerView mRvTask;
    @BindView(R.id.iv_left_back)
    ImageView mIvLeftBack;
    @BindView(R.id.iv_right_other)
    ImageView mIvRightOther;
    @BindView(R.id.v_shadow)
    View mVShadow;
    private MyTaskAdapter mAdapter;
    private View mEmptyView;
    private View mEmptyLoadView;
    private PopupWindow mPopupWindow;
    private QBadgeView mQBadgeView;
    private CommonDialog mSignDialog;

    private void showTypeChooseWindow(View v) {

        final ListView rvTypeChoose = (ListView) getLayoutInflater().inflate(R.layout.window_type_choose, null);
        final List<String> strings = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            strings.add("类型" + i);
        }

        BusinessTypeAdapter adapter = new BusinessTypeAdapter(strings);
        rvTypeChoose.setAdapter(adapter);
        rvTypeChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                mTvTypeShow.setText(strings.get(position));
                mPopupWindow.dismiss();

            }
        });

        mPopupWindow = new PopupWindow(v);
        mPopupWindow.setWidth(v.getWidth() + DeviceUtils.dp2px(mContext, 30));
        mPopupWindow.setHeight(v.getHeight() * strings.size());
        mPopupWindow.setAnimationStyle(R.style.popupWindow_top_scale_show);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setContentView(rvTypeChoose);
        setPopupWindowBack(0.5F);
        mPopupWindow.showAsDropDown(v);
        rvTypeChoose.setItemChecked(0,true);

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                setPopupWindowBack(1F);
                mIvMore.setImageResource(R.drawable.ic_expand_true);

            }
        });

    }

    private void setPopupWindowBack(Float alpha) {

//        MainActivity activity = (MainActivity) mContext;
//        Window window = activity.getWindow();
//        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.alpha = alpha;
//        window.setAttributes(lp);
        if(alpha == 1) {

            mVShadow.setVisibility(View.GONE);
        } else {

            mVShadow.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected View bindView(ViewGroup container) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_my_task, container, false);

        return view;
    }

    @Override
    protected void initView() {


        OrderRepository.getInstance(OrderLocalDataSource.getInstance(), OrderRemoteDataSource.getInstance())
                .getMyOrderList(new OrderDataSource.LoadMyOrderListCallBack() {
            @Override
            public void onMyOrderListLoaded(List<OrderBrief> orderList) {
                Log.i(TAG, "onMyOrderListLoaded: ");
            }

            @Override
            public void onDataLoadedFailure() {
                Log.i(TAG, "onDataLoadedFailure: ");
            }
        });



        int stateHeight = DeviceUtils.getStateHeight(mContext);
        ViewGroup.LayoutParams params = mVState.getLayoutParams();
        params.height = stateHeight;
        mVState.setLayoutParams(params);

        mTvTitle.setText(ResourceUtils.getString(R.string.wait_done_task));

        mQBadgeView = new QBadgeView(mContext);
        mQBadgeView.bindTarget(mIvRightMore)
                .setBadgeNumber(9)
                .setBadgeBackgroundColor(Color.WHITE)
                .setBadgeTextColor(ResourceUtils.getColor(R.color.colorPrimary))
                .setBadgeGravity(Gravity.END | Gravity.TOP)
                .setBadgeTextSize(12,true)
                .setGravityOffset(0F, 0F, true);

        mIvRightMore.setImageResource(R.drawable.ic_bar_message);
        mIvRightMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /*boolean empty = TextUtils.isEmpty(DemoCache.getAccount());
                if (empty) {

                    startActivity(LoginActivity.class);

                } else {


                    startActivity(IMMainActivity.class);
                }*/

                startActivity(NotificationMessageActivity.class);
                mQBadgeView.setBadgeNumber(0);
            }
        });

        mIvLeftBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(LootAssignmentActivity.class);
            }
        });

        mIvRightOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(MyScheduleActivity.class);
            }
        });

        mRgDateChoose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.rb_today:

                        ToastUtils.tMessage("点击了今天");

                        break;
                    case R.id.rb_tomorrow:

                        ToastUtils.tMessage("点击了明天");

                        break;
                    case R.id.rb_one_week:
                        ToastUtils.tMessage("点击了一周");


                        break;
                    case R.id.rb_all_date:

                        ToastUtils.tMessage("点击了所有");

                        break;
                    default:
                        break;
                }
            }
        });

        mLlTypeChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(mPopupWindow == null) {

                    showTypeChooseWindow(v);
                } else {

                    mPopupWindow.showAsDropDown(v);
                    setPopupWindowBack(0.5F);
                }

                mIvMore.setImageResource(R.drawable.ic_expand_false);
            }
        });

        mIvMore.setColorFilter(Color.BLACK);
    }

    @Override
    protected void initData() {

        initList();
    }

    private void initList() {

        mSrlTask.setColorSchemeColors(mContext.getResources().getColor(R.color.colorPrimary));
        mRvTask.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mRvTask.setHasFixedSize(true);

        mEmptyView = getLayoutInflater().inflate(R.layout.item_load_empty, (ViewGroup) mRvTask.getParent(), false);
        mEmptyLoadView = getLayoutInflater().inflate(R.layout.item_load_empty_loading, (ViewGroup) mRvTask.getParent(), false);

        mEmptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mAdapter.setEmptyView(mEmptyLoadView);
                refreshData();
            }
        });

        List<String> strings = new ArrayList<>();

        mAdapter = new MyTaskAdapter(strings);
        mRvTask.setAdapter(mAdapter);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mRvTask.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(mContext)
                        .colorResId(R.color.space)
                        .size(DeviceUtils.dp2px(mContext,10))
                        .build());
//        mAdapter.setEmptyView(R.layout.item_load_empty_loading, (ViewGroup) mRvTask.getParent());
//        mAdapter.disableLoadMoreIfNotFullPage();

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {

                getMoreData();
            }
        }, mRvTask);

        mSrlTask.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                refreshData();
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {

                startActivity(TaskDetailsActivity.class);
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                int id = view.getId();
                switch (id) {
                    case R.id.iv_call_phone:

                        jump2Call("10086");
                        break;

                    case R.id.iv_send_message:

                        ToastUtils.tMessage("跳到通讯界面");
                        break;

                    case R.id.rl_came_here :

                        jump2Map("天安门",39.915087,116.403945);
                        break;

                    case R.id.rl_go_sign :

                        showGoSign(position);
                        break;

                    default:
                        break;
                }
            }
        });

        refreshData();
    }

    private void showGoSign(final int position) {

        if(mSignDialog == null) {

            mSignDialog = new CommonDialog(mContext, ResourceUtils.getString(R.string.confirm_go_sign));

        }
        mSignDialog.show();

        mSignDialog.setOnConfirmListener(new CommonDialog.OnConfirmListener() {
            @Override
            public void setOnConfirmClick(CommonDialog instance) {

                instance.dismiss();
                Toast.makeText(mContext, "已签到" + position, Toast.LENGTH_SHORT).show();
                startActivity(TaskDetailsActivity.class);
            }
        });
    }

    private void jump2Call(String phone) {


        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        mContext.startActivity(intent);
    }

    private void jump2Map(String address, double lat, double lon) {

        Jump2MapUtils.getInstance().signMap(mContext,address,lat,lon);
    }

    private Disposable mDisposable;

    private void refreshData() {

        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {

                SystemClock.sleep(1000L);

                List<String> strings = new ArrayList<>();
                for (int i = 0; i < 5; i++) {

                    strings.add("刷新的数据的数据");
                }
                emitter.onNext(strings);
            }
        }).subscribeOn(Schedulers.io())
          .doOnSubscribe(new Consumer<Disposable>() {
              @Override
              public void accept(Disposable disposable) throws Exception {

                  mDisposable = disposable;
                  mSrlTask.setRefreshing(true);
                  mAdapter.setEnableLoadMore(false);
              }
          }).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<String>>() {
                @Override
                public void accept(List<String> s) throws Exception {

                    Toast.makeText(mContext, "数据刷新成功", Toast.LENGTH_SHORT).show();
                    mAdapter.setNewData(s);
                    mAdapter.loadMoreComplete();

                    mAdapter.setEnableLoadMore(true);
                    mSrlTask.setRefreshing(false);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {

                }
            });
    }

    private void getMoreData() {

        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {

                SystemClock.sleep(2000L);

                List<String> strings = new ArrayList<>();
                for (int i = 0; i < 5; i++) {

                    strings.add("更多的数据");
                }
//                emitter.onNext(strings);
                emitter.onError(new Throwable("111"));
            }
        }).subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(new Consumer<List<String>>() {
              @Override
              public void accept(List<String> s) throws Exception {

                  mAdapter.addData(s);
                  mAdapter.loadMoreComplete();
//                  mAdapter.loadMoreEnd(true);
              }
          }, new Consumer<Throwable>() {
              @Override
              public void accept(Throwable throwable) throws Exception {

                   mAdapter.loadMoreFail();
              }
          });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if(mDisposable != null && !mDisposable.isDisposed()) {

            mDisposable.dispose();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void cancelOrder(OrderStateEvent event){

        boolean cancel = event.isCancel();
        if(cancel) {

            refreshData();
        }
    }

    @Override
    public boolean onBackPressed() {

        if(mPopupWindow != null && mPopupWindow.isShowing()) {

            mPopupWindow.dismiss();
            return true;
        } else {

            return false;
        }
    }
}
